<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <el-row :gutter="5">
        <el-col :span="24" class="main-card-view">
          <el-row>
            <el-card shadow="never" class="top-search-view-card">
              <el-row>
                <el-form :inline="true" :model="searchForm" class="demo-form-inline search-view">
                  <el-form-item label="关键字">
                    <el-input v-model="searchForm.keyWord" placeholder="请输入关键字"></el-input>
                  </el-form-item>
                  <el-form-item label="分类">
                    <el-select v-model="searchForm.type" placeholder="请选择">
                      <el-option v-for="item in typeList" :key="item" :label="item" :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleSearch" class="search-button">查询</el-button>
                    <!--                                        <el-button type="success" @click="handleReset" class="reset-button">重置</el-button>-->
                    <el-button type="primary" @click="showCreateDialog" class="new-button">添加</el-button>
                  </el-form-item>
                </el-form>
              </el-row>
            </el-card>
          </el-row>

          <el-row>
            <el-card shadow="never">
              <el-table :data="tableData" :stripe="true" style="width: 100%">
                <el-table-column prop="subjectName" align="center" label="题目" />
                <el-table-column prop="score" align="center" label="分值" />
                <el-table-column prop="type" align="center" label="类型" />
                <el-table-column prop="createTime" align="center" label="添加时间" />
                <el-table-column prop="publishName" align="center" label="发布者" />
                <el-table-column align="center" label="操作" width="200">
                  <template slot-scope="scope">
                    <el-button type="text" class="table-edit-btn"
                      @click="showEditDialog(scope.$index, scope.row)"></el-button><!--编辑-->
                    <el-button type="text" class="table-delete-btn"
                      @click="handleDelete(scope.$index, scope.row)"></el-button><!--删除-->
                  </template>
                </el-table-column>
              </el-table>
              <XPagination ref="pageInfo" :total="total" :get-data="getList" />
            </el-card>
          </el-row>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form label-width="120px" ref="form" :model="form" :rules="formRules">
        <el-form-item label="分类" prop="type">
          <el-select v-model="form.type" placeholder="请选择" :disabled="dialogTitle === '编辑'" @change="typeChange">
            <el-option v-for="item in typeList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目" prop="activityName">
          <el-input v-model="form.subjectName" />
        </el-form-item>
        <el-form-item label="答案" v-if="form.type === '判断题'">
          <el-radio v-model="form.result" label="对">对</el-radio>
          <el-radio v-model="form.result" label="错">错</el-radio>
        </el-form-item>
        <el-form-item label="选项" v-if="form.type === '单选题' || form.type === '多选题'">
          <div style="display: flex;margin-bottom:20px ;" v-for="item in choice" :key="item.options">
            <span style="margin-right: 20px;">{{ item.options }}</span>
            <el-input v-model="item.value" />
          </div>
          <div>
            <el-button @click="addChoice">增加选项</el-button>
            <el-button @click="choice.pop()">删除选项</el-button>
          </div>
        </el-form-item>
        <el-form-item label="答案" v-if="form.type === '单选题'">
          <el-radio-group v-model="form.result">
            <el-radio v-for="item in choice" :key="item.options" :label="item.options"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="答案" v-if="form.type === '多选题'">
          <el-checkbox-group v-model="form.result">
            <el-checkbox v-for="item in choice" :key="item.options" :label="item.options"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="答案" v-if="form.type === '填空题'">
          <div style="margin-bottom: 20px;" v-for="(item, i) in gapFilling" :key="i">
            <el-input v-model="item.value" />
          </div>
          <div>
            <el-button @click="addGapFilling">增加填空</el-button>
            <el-button @click="gapFilling.pop()">删除填空</el-button>
          </div>
        </el-form-item>
        <el-form-item label="每空分值" prop="activityName">
          <el-input v-model="form.score" />
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import XPagination from "../../components/xpagination/XPagination";
import XUpload from "../../components/xupload/XUpload"
import * as TopicManger from "../../api/TopicManger"
import * as formUtils from "../../utils/formUtils";
export default {
  components: { XPagination, XUpload },
  data () {
    return {
      searchForm: {
      },
      tableData: [],
      loading: false,
      dialogVisible: false,
      treeDialog: false,
      total: 0,
      dialogTitle: "添加",
      form: {
        result: ''
      },
      timer: [],
      editStatus: "add",
      formRules: {
        description: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
      },
      checkedArr: [],
      defaultProps: {
        children: 'children',
        label: 'columnName'
      },
      roleId: '',
      positionOne: false,
      positionsTwo: false,
      typeList: [
        '单选题',
        '多选题',
      ],
      letter: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
        'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      choice: [
        { options: 'A', value: "" },
        { options: 'B', value: "" },
        { options: 'C', value: "" },
        { options: 'D', value: "" },
      ],
      gapFilling: [{ value: '' }]
    }
  },
  methods: {
    getList (pageInfo) {
      const param = {
        ...this.searchForm,
        ...pageInfo
      }
      TopicManger.queryByPage(param).then(response => {
        console.log(response)
        this.tableData = response.data.data.rows
        this.total = response.data.data.total
        this.loading = false
      }).catch(error => {
        console.log(error)
      })
    },
    handleDelete (index, data) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = {
          uid: data.uid,
        }
        this.loading = true
        TopicManger.deleteById(param).then(result => {
          this.loading = false
          this.$message.success(result.data.msg)
          this.handleSearch()
        }).catch(error => {
          this.loading = false
          console.log(error)
        })
      }).catch(() => {
        console.log('取消删除')
      });
    },
    handleSearch () {
      this.$refs.pageInfo.loadData()
    },
    showCreateDialog () {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.dialogTitle = "添加"
        this.editStatus = "add"
        this.$refs.form.resetFields()
        this.form = {
          result: ''
        }
        this.choice = [
          { options: 'A', value: "" },
          { options: 'B', value: "" },
          { options: 'C', value: "" },
          { options: 'D', value: "" },
        ],
          this.gapFilling = [{ value: '' }]
      })
    },
    handleSave () {
      console.log(this.form)
      if (this.form.type === '单选题' || this.form.type === '多选题') {
        this.form.alternatives = JSON.stringify(this.choice)
      }
      if (this.form.type === '填空题') {
        this.form.result = JSON.stringify(this.gapFilling)
      }
      if (this.form.type === '多选题') {
        this.form.result = JSON.stringify(this.form.result)
      }
      if (this.editStatus === "add") {
        this.handleAdd()
      } else {
        this.handleEdit()
      }
    },
    handleAdd () {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false
        }
        const param = Object.assign({}, this.form)
        formUtils.filterFormFields(param)
        param.publishName = localStorage.getItem('username')
        TopicManger.insert(param).then(result => {
          this.$message.success(result.data.msg)
          this.dialogVisible = false
          this.handleSearch()
        }).catch(error => {
          this.$message.error(error)
          console.log(error)
        })

      })
    },
    handleEdit () {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false
        }
        const param = Object.assign({}, this.form)
        formUtils.filterFormFields(param)
        TopicManger.update(param).then(result => {
          this.$message.success(result.data.msg)
          this.dialogVisible = false
          this.handleSearch()
        }).catch(error => {
          this.$message.error(error)
          console.log(error)
        })
      })
    },
    showEditDialog (index, data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.form = Object.assign({}, data)
        this.choice = JSON.parse(this.form.alternatives)
        if (this.form.type === '填空题') {
          this.gapFilling = JSON.parse(this.form.result)
        }
        if (this.form.type === '单选题' || this.form.type === '多选题') {
          this.choice = JSON.parse(this.form.alternatives)
        }
        if (this.form.type === '多选题') {
          this.form.result = JSON.parse(this.form.result)
        }
        this.dialogTitle = "编辑"
        this.editStatus = "edit"
      })
    },
    addChoice () {
      let num = this.choice.length
      let options = this.letter[num]
      this.choice.push({
        options: options, value: ""
      })
    },
    addGapFilling () {
      this.gapFilling.push({ value: "" })
    },
    typeChange (e) {
      if (e === '多选题') {
        this.form.result = []
      }
    }
  },
  mounted () {
    this.handleSearch()
  }
}
</script>

<style scoped lang="scss"></style>
